import uuid
from flask import Blueprint, request
from static.connect.conn_mysql import Connect

app_login = Blueprint('app_login', __name__)


@app_login.route('/login', methods=['POST'])
def login():
    info = request.form
    phone = info.get('phone')
    pass_word = info.get('pass_word')
    if not all([phone, pass_word]):
        return {
            'status': -1,
            'errorCode': 1,
            'errorMsg': '账号密码不能为空',
            'resultBody': '失败'
        }
    with Connect() as C:
        select_sql = 'select * from users where user=%s and pass_word=%s'
        result = C.select_one(select_sql, (phone, pass_word))
        if not result:
            return {
                'status': -1,
                'errorCode': 2,
                'errorMsg': '你的手机号码还没有注册请先注册',
                'resultBody': '失败'
            }
        else:
            access_token = uuid.uuid1().hex
            user_id = result['id']
            with Connect() as c:
                insert_sql = 'insert into access_token(user_id,access_token) values(%s,%s)'
                c.insert(insert_sql, (user_id, access_token))
            return {
                'status': 1,
                'errorCode': 6,
                'errorMsg': None,
                'resultBody': {'info': '登录成功', 'access_token': access_token, 'user_id': user_id}
            }
